export const ui = {
  delayToast(timeout, success, msg, cb) {
    const that = this
    setTimeout(() => {
      that.toast(success, msg, cb)
    }, timeout);
  },
  toast: (success, msg, cb) => {
    const duration = 1500
    msg = msg?.result?.errMsg || msg || ''
    wx.showToast({
      title: msg || (success ? '操作成功' : '操作失败'),
      icon: (msg.length > 7 && 'none') || (success && 'success') || 'error',
      duration,
      mask: true,
      complete: (success) => {
        if (!cb) return
        setTimeout(() => {
          cb(success)
        }, duration)
      }
    })
  },
  actionSheet: (item, cb) => { // item: {key: value, ...}
    let itemList = []
    if (item instanceof Array) {
      itemList = item
      item = {}
      itemList.forEach(ele => item[ele] = ele)
    } else if (item instanceof Object)
      itemList = Object.values(item)
    wx.showActionSheet({
      itemList,
      success: function (res) {
        const desc = itemList[res.tapIndex],
          key = Object.keys(item)[res.tapIndex]
        if (cb) cb(desc, key)
      },
      fail: function (res) {
        if (!res.errMsg.endsWith(":fail cancel"))
          console.error(res)
      }
    })
  },
  actionSheetx: (options, cb) => { // options: [{name, value}, ...]
    const itemList = []
    for (const item of options) itemList.push(item.name)
    wx.showActionSheet({
      itemList,
      success: function (res) { // res: {name, value}
        if (cb) cb(options[res.tapIndex])
      },
      fail: function (res) {
        if (!res.errMsg.endsWith(":fail cancel"))
          console.error(res)
      }
    })
  },
  confirm: (msg, cb) => {
    wx.showModal({
      title: '提示',
      content: msg,
      success: function (sm) {
        if (cb) cb(sm.confirm)
      }
    })
  },
  confirmx: (msg) => {
    return new Promise((resolve, reject) => {
      wx.showModal({
        title: '提示',
        content: msg,
        success: function (sm) {
          resolve(sm.confirm)
        }
      })
    })
  },
  text: (title, msg, cb) => {
    wx.showModal({
      title: title || '请输入',
      editable: true, //显示输入框
      placeholderText: (msg + '') || '请输入', //显示输入框提示信息
      success: res => {
        if (cb) cb(res.confirm, res.content)
      }
    })
  },
  loading: (show, title, cb) => {
    if (show !== false) {
      wx.showLoading({
        title: title || '加载中...',
        mask: true,
        success: () => {
          if (cb) cb()
        }
      })
    } else {
      wx.hideLoading()
    }
  },
  finish(success, msg) {
    ui.loading(false)
    if (msg) this.toast(success, msg)
  },
  makePhoneCall(number) {
    wx.makePhoneCall({
      phoneNumber: number,
    })
  },
  eventData(e, name) {
    return e.currentTarget.dataset[name]
  },
  eventDataset(e) {
    return e.target.dataset
  },
  rpx2px(rpx) {
    const screenWidth = wx.getSystemInfoSync().screenWidth
    return (screenWidth * Number.parseInt(rpx)) / 750
  },
  px2rpx(px) {
    const screenWidth = wx.getSystemInfoSync().screenWidth
    return (750 * Number.parseInt(px)) / screenWidth
  },
  defaultAvatarUrl() {
    return getApp().globalData.cloudPrefix + '/static/img/defaultAvatar@2x.png'
  },
  getCloudFileUrl(fileID, cb) {
    const that = this
    if (!fileID) return
    if (!wx.cloud) {
      console.error('请使用 2.2.3 或以上的基础库以使用云能力');
      return;
    }
    wx.cloud.getTempFileURL({
      fileList: [fileID],
      success: res => {
        const tempFilePath = res.fileList[0].tempFileURL; // 获取到的临时链接
        if (cb) cb(tempFilePath)
      },
      fail: err => {
        console.error('获取临时链接失败', err);
      }
    });
  },
  scrollTo(id, duration = 300) {
    const query = wx.createSelectorQuery();
    query.select(`#${id}`).boundingClientRect((rect) => {
      if (rect) {
        wx.pageScrollTo({
          scrollTop: rect.top,
          duration
        });
      }
    }).exec();
  }
}